package com.treasure.mall.zbqmallmanager.controller.order;

import com.treasure.mall.biz.dto.condition.DeliverBillCondition;
import com.treasure.mall.biz.entity.order.DeliverBillPO;
import com.treasure.mall.biz.remote.track.LogisticsProvider;
import com.treasure.mall.biz.remote.track.dto.ReceiveInfo;
import com.treasure.mall.biz.service.core.order.DeliverService;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.base.ResultCodeEnum;
import com.treasure.mall.zbq.common.constant.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/6/12
 */
@Controller
@RequestMapping("/order/deliver")
public class DeliverController {
    @Autowired
    private DeliverService deliverService;
    @Autowired(required = false)
    private LogisticsProvider logisticsProvider;

    @GetMapping("/list")
    public String list(
            @ModelAttribute("condition") DeliverBillCondition condition,
            @RequestParam(required = false, defaultValue = "1") int pageIndex,
            Model model
    ) {
        Page<DeliverBillPO> orderPOS = deliverService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE, condition);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", orderPOS.getTotalElements());
        model.addAttribute("totalPages", orderPOS.getTotalPages());
        model.addAttribute("bills", orderPOS.getContent());

        return "order/deliver_list";
    }

    @PostMapping("/queryTrack")
    @ResponseBody
    public ApiResult queryTrack(String id) {
        return ApiResult.resultWith(ResultCodeEnum.SUCCESS, deliverService.queryTrack(id));
    }

    /**
     * 快递服务订阅推送
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @PostMapping("/callback")
    public void subscribe(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ReceiveInfo receiveInfo = logisticsProvider.subCallback(request);

        deliverService.receive(receiveInfo);

        logisticsProvider.callbackResp(response);
    }
}
